package com.qdc.datacenters.interceptor.forest;

import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestRequestType;
import com.qdc.datacenters.client.CorpTokenClient;
import com.qdc.datacenters.config.redis.RedisService;
import com.qdc.datacenters.constant.CacheConstants;
import com.qdc.datacenters.domain.entity.SysCorp;
import com.qdc.datacenters.domain.query.corp.SysCorpQuery;
import com.qdc.datacenters.domain.query.qw.QwBaseQuery;
import com.qdc.datacenters.domain.query.qw.QwCustomerQuery;
import com.qdc.datacenters.domain.vo.qw.CorpTokenVo;
import com.qdc.datacenters.exception.QwAbutmentException;
import com.qdc.datacenters.service.ISysCorpService;
import com.qdc.datacenters.utils.StrUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author danmo
 * @date 2024-03-01 14:36
 **/
@Slf4j
@Component
public abstract class ForestBaseInterceptor {

    @Autowired
    private ISysCorpService iSysCorpService;

    @Autowired
    private RedisService redisService;

    @Resource
    private CorpTokenClient corpTokenClient;


    protected String getCorpId(ForestRequest request) {
        String corpId;
        Map<String, Object> baseQuery = request.getBody().nameValuesMapWithObject();
        if (baseQuery == null || baseQuery.get("corpid") == null) {
            QwBaseQuery query = (QwBaseQuery) request.getVariableValue("query");
            corpId = query.getCorpid();
            if (request.getVariableValue("query") instanceof QwCustomerQuery) {
                QwCustomerQuery customerQuery = (QwCustomerQuery) request.getVariableValue("query");
                if (request.getType().getName().equals(ForestRequestType.GET.getName()) && StrUtils.isNotEmpty(customerQuery.getCursor())) {
                    request.addQuery("cursor", customerQuery.getCursor());
                }
            }
        } else {
            corpId = baseQuery.get("corpid") == null ? null : String.valueOf(baseQuery.get("corpid"));
        }
        return corpId;
    }


    String getChatAccessToken(String corpId) {
        String accessTokenKey = StrUtils.format(CacheConstants.CHAT_MSG_ACCESS_TOKEN, corpId);
        String accessToken = redisService.getCacheObject(accessTokenKey);
        if (StringUtils.isEmpty(accessToken)) {
            SysCorp sysCorp = iSysCorpService.get(SysCorpQuery.builder().corpId(corpId).build());
            if (Objects.isNull(sysCorp)) {
                //返回错误异常，让用户绑定企业id相关信息
                throw new QwAbutmentException("corpId or secret is null");
            }
            CorpTokenVo corpTokenVo = corpTokenClient.getToken(sysCorp.getCorpId(), sysCorp.getChatSecret());
            if (Objects.nonNull(corpTokenVo) && StrUtils.isNotEmpty(corpTokenVo.getAccessToken())) {
                accessToken = corpTokenVo.getAccessToken();
                redisService.setCacheObject(accessTokenKey, corpTokenVo.getAccessToken(), corpTokenVo.getExpiresIn(), TimeUnit.SECONDS);
            }
        }
        return accessToken;
    }

    String getAgentAccessToken(String corpId){
        String accessTokenKey = StrUtils.format(CacheConstants.AGENT_MSG_ACCESS_TOKEN, corpId);
        String accessToken = redisService.getCacheObject(accessTokenKey);
        if (StringUtils.isEmpty(accessToken)) {
            SysCorp sysCorp = iSysCorpService.get(SysCorpQuery.builder().corpId(corpId).build());
            if (Objects.isNull(sysCorp)) {
                //返回错误异常，让用户绑定企业id相关信息
                throw new QwAbutmentException("corpId or secret is null");
            }
            CorpTokenVo corpTokenVo = corpTokenClient.getToken(sysCorp.getCorpId(), sysCorp.getAgentSecret());
            if (Objects.nonNull(corpTokenVo) && StrUtils.isNotEmpty(corpTokenVo.getAccessToken())) {
                accessToken = corpTokenVo.getAccessToken();
                redisService.setCacheObject(accessTokenKey, corpTokenVo.getAccessToken(), corpTokenVo.getExpiresIn(), TimeUnit.SECONDS);
            }
        }
        return accessToken;
    }


    public void removeChatAccessToken(String corpId) {
        redisService.deleteObject(StrUtils.format(CacheConstants.CHAT_MSG_ACCESS_TOKEN, corpId));
    }

    public void removeAgentAccessToken(String corpId) {
        redisService.deleteObject(StrUtils.format(CacheConstants.AGENT_MSG_ACCESS_TOKEN, corpId));
    }
}
